package com.panda.pandawash.activity;

/**
 * Created by huangyusheng on 17-1-13.
 */

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.panda.pandawash.R;
import com.panda.pandawash.application.CDApplication;
import com.panda.pandawash.bean.HttpResultBean;
import com.panda.pandawash.bean.UserBean;
import com.panda.pandawash.util.HttpUtil;
import com.panda.pandawash.util.StringUtil;
import com.panda.pandawash.util.WsUtils;
import com.panda.pandawash.view.StatusBarCompat;

import java.util.ArrayList;

public class RegisterActivity extends Activity implements OnClickListener {
    private static String TAG = "API_TAG";
    private int time = 60;
    private EditText mUserAccountEt;
    private EditText mPasswordEt;
    private EditText mPasswordRepeatEt;
    private EditText mRegisteIdCodeEt;
    private Button mRegisteBt;
    private Button mGetIdCodeBt;
    private ImageButton mBack;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            StatusBarCompat.compat(this, getResources().getColor(R.color.colorPrimary));
        }

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads().detectDiskWrites().detectNetwork()
                .penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
                .penaltyLog().penaltyDeath().build());

        initView();
        setListener();
    }

    private void initView() {
        mUserAccountEt = (EditText) findViewById(R.id.edit_phone_number);
        mPasswordEt = (EditText) findViewById(R.id.edit_password);
        mPasswordRepeatEt = (EditText) findViewById(R.id.edit_password_repeat);
        mRegisteIdCodeEt = (EditText) findViewById(R.id.edit_sms_number);
        mRegisteBt = (Button) findViewById(R.id.btn_register);
        mGetIdCodeBt = (Button) findViewById(R.id.btn_get_sms_number);
        mBack = (ImageButton) findViewById(R.id.btn_return);
    }

    private void setListener() {
        mRegisteBt.setOnClickListener(this);
        mGetIdCodeBt.setOnClickListener(this);
        mBack.setOnClickListener(this);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        excuteBack();
    }

    private void excuteBack(){
        Intent mIntent = new Intent(RegisterActivity.this, LoginActivity.class);
        RegisterActivity.this.startActivity(mIntent);
        RegisterActivity.this.finish();
    }

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            time--;
            mGetIdCodeBt.setText("" + time);
            handler.postDelayed(this, 1000);
            if (time <= 0) {
                handler.removeCallbacks(runnable);
                mGetIdCodeBt.setClickable(true);
                mGetIdCodeBt.setText("发送验证码");
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_register:
                doRegist();
                break;
            case R.id.btn_get_sms_number:
                getIdCode();

                break;
            case R.id.btn_return:
                excuteBack();
                break;
        }
    }

    private void doRegist() {
        String username = mUserAccountEt.getText().toString().trim();
        String idCode = mRegisteIdCodeEt.getText().toString().trim();
        String password = mPasswordEt.getText().toString().trim();
        String passwordRepeat = mPasswordRepeatEt.getText().toString().trim();

        if (!WsUtils.isPhoneNumber(username)) {
            Toast.makeText(this, R.string.registe_incorrect_username, Toast.LENGTH_SHORT).show();
            mUserAccountEt.requestFocus();
            return;
        }

        if(TextUtils.isEmpty(mRegisteIdCodeEt.getText().toString().trim())){
            Toast.makeText(this, R.string.registe_idcode_empty, Toast.LENGTH_SHORT).show();
            mRegisteIdCodeEt.requestFocus();
            return;
        }

        if (!WsUtils.isMatch(WsUtils.REGEX_PASSWORD,password)) {
            Toast.makeText(this, R.string.registe_password_legal, Toast.LENGTH_SHORT).show();
            mPasswordEt.requestFocus();
            return;
        }

        if((!password.equals(password.trim()))||(!passwordRepeat.equals(passwordRepeat.trim()))){
            Toast.makeText(this, R.string.registe_password_have_space, Toast.LENGTH_SHORT).show();
            mPasswordEt.requestFocus();
            return;
        }
        if(!password.trim().equals(passwordRepeat.trim())){
            Toast.makeText(this, R.string.registe_password_not_same, Toast.LENGTH_SHORT).show();
            mPasswordEt.requestFocus();
            return;
        }

        HttpUtil.loginWithIdCode(new RegisteInfoCallback(), username, username, password, idCode);
    }

    private void getIdCode() {
        String userAccount = mUserAccountEt.getText().toString().trim();
        if (!WsUtils.isPhoneNumber(userAccount)) {
            Toast.makeText(this, R.string.registe_incorrect_username, Toast.LENGTH_SHORT).show();
            return;
        }
        mGetIdCodeBt.setClickable(false);
        time = 60;
        runnable.run();
        HttpUtil.getIdCode(new SendIdCodeCallback(), userAccount, userAccount);
    }

    private class SendIdCodeCallback extends AsyncHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, String content) {
            super.onSuccess(statusCode, content);
            Log.d(TAG, "SendIdCodeCallback statusCode = " + statusCode);
            Log.d(TAG, "SendIdCodeCallback onSuccess = " + content);
            if (statusCode == 200) {
                HttpResultBean resultBean = HttpUtil.parserHttpResultInfo(content, "user");
                Log.d(TAG, "resultBean = " + resultBean);
                if (resultBean != null) {
                    String code = resultBean.getCode();
                    String message = resultBean.getMessage();
                    Log.d(TAG, "code = " + code);
                    if(code.equals("0")){
                        Toast.makeText(RegisterActivity.this, R.string.registe_idcode_success,Toast.LENGTH_LONG).show();
                    }else if(code.equals("99")){
                        Toast.makeText(RegisterActivity.this, message,Toast.LENGTH_LONG).show();
                    }
                }
            } else {
                Toast.makeText(RegisterActivity.this, R.string.registe_idcode_fail,Toast.LENGTH_LONG).show();
            }
        }
    }

    private class RegisteInfoCallback extends AsyncHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, String content) {
            super.onSuccess(statusCode, content);
            Log.d(TAG, "RegisteInfoCallback statusCode = " + statusCode);
            Log.d(TAG, "RegisteInfoCallback onSuccess = " + content);
            if (statusCode == 200) {
                HttpResultBean resultBean = HttpUtil.parserHttpResultInfo(content, "user");
                Log.d(TAG, "resultBean = " + resultBean);
                if (resultBean != null) {
                    String code = resultBean.getCode();
                    String message = resultBean.getMessage();
                    Log.d(TAG, "code = " + code);
                    if(code.equals("0")){
                        registSuccess();
                        showMessage(getString(R.string.registe_success));
                    }else if(code.equals("99")){
                        showMessage(message);
                    }
                }
            } else {
                showMessage(getString(R.string.registe_fail));

            }
        }
    }

    private void  registSuccess(){
        CDApplication.getIntance().setLoginStatus(true);
        UserBean user = CDApplication.getIntance().getUserInfo();
        user.setUseraccount(mUserAccountEt.getText().toString().trim());
        user.setUserpassword(mPasswordEt.getText().toString().trim());
        CDApplication.getIntance().saveUserInfo(user);
        Intent mIntent = new Intent(RegisterActivity.this, PandaWashActivity.class);
        mIntent.putExtra("firstLogin",true);
        CDApplication.getIntance().getPreferenceUtils().setBoolean("firstLogin",true);
        RegisterActivity.this.startActivity(mIntent);
        RegisterActivity.this.finish();
    }
    private void showMessage(String string) {
        Toast toast = Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }
}